package com.weatherstation.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.weatherstation.entity.DeviceInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 设备信息Mapper接口
 */
@Mapper
public interface DeviceInfoMapper extends BaseMapper<DeviceInfo> {
    
    /**
     * 根据设备名称查找设备
     */
    @Select("SELECT * FROM device_info WHERE device_name = #{deviceName} LIMIT 1")
    DeviceInfo findByDeviceName(@Param("deviceName") String deviceName);
    
    /**
     * 根据设备类型查找设备列表
     */
    @Select("SELECT * FROM device_info WHERE device_type = #{deviceType}")
    List<DeviceInfo> findByDeviceType(@Param("deviceType") String deviceType);
    
    /**
     * 根据设备状态查找设备列表
     */
    @Select("SELECT * FROM device_info WHERE status = #{status}")
    List<DeviceInfo> findByStatus(@Param("status") Integer status);
    
    /**
     * 查找在线设备（最近心跳时间在指定时间之后）
     */
    @Select("SELECT * FROM device_info WHERE last_heartbeat >= #{timeThreshold}")
    List<DeviceInfo> findOnlineDevices(@Param("timeThreshold") LocalDateTime timeThreshold);
    
    /**
     * 查找离线设备（最近心跳时间在指定时间之前）
     */
    @Select("SELECT * FROM device_info WHERE last_heartbeat < #{timeThreshold}")
    List<DeviceInfo> findOfflineDevices(@Param("timeThreshold") LocalDateTime timeThreshold);
    
    /**
     * 统计在线设备数量
     */
    @Select("SELECT COUNT(*) FROM device_info WHERE last_heartbeat >= #{timeThreshold} AND status = 1")
    Long countOnlineDevices(@Param("timeThreshold") LocalDateTime timeThreshold);
    
    /**
     * 统计离线设备数量
     */
    @Select("SELECT COUNT(*) FROM device_info WHERE last_heartbeat < #{timeThreshold} OR status = 0")
    Long countOfflineDevices(@Param("timeThreshold") LocalDateTime timeThreshold);
    
    /**
     * 根据位置查找设备
     */
    @Select("SELECT * FROM device_info WHERE location LIKE CONCAT('%', #{location}, '%')")
    List<DeviceInfo> findByLocationContaining(@Param("location") String location);
    
    /**
     * 获取所有正常状态的设备
     */
    @Select("SELECT * FROM device_info WHERE status = #{status} ORDER BY created_at DESC")
    List<DeviceInfo> findByStatusOrderByCreatedAtDesc(@Param("status") Integer status);
    
    /**
     * 检查设备名称是否存在
     */
    @Select("SELECT COUNT(*) FROM device_info WHERE device_name = #{deviceName}")
    int existsByDeviceName(@Param("deviceName") String deviceName);
} 